package com.bbs.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbs.common.entity.Forum;
import com.bbs.common.entity.User;
import com.bbs.common.exception.CommonException;
import com.bbs.common.mapper.ForumMapper;
import com.bbs.common.vo.PageVo;
import com.bbs.dto.ForumListDTO;
import com.bbs.dto.UserListDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ForumService {

    @Autowired
    private ForumMapper forumMapper;

    // 列表展示
    public PageVo<Forum> list(ForumListDTO listDTO) {
        System.out.println(listDTO.getCurrentPage());
        // 返回的分页条件
        Page<Forum> queryPage = new Page<>(listDTO.getCurrentPage(), listDTO.getPageSize());
        // 查询条件
        QueryWrapper<Forum> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(listDTO.getTitle())) {
            queryWrapper.lambda().like(Forum::getTitle, listDTO.getTitle());
        }
        queryWrapper.lambda().eq(Forum::getDeleteFlag, 0).orderByDesc(Forum::getCreateTime); // 查询筛选，查询未删除的然后显示
        IPage<Forum> list = forumMapper.selectPage(queryPage, queryWrapper);
        System.out.println(list);
        return new PageVo<>(list);
    }

    // 删除
    public void delete(int id) {
        Forum forum = forumMapper.selectById(id);
        if(forum == null) {
            throw new CommonException("帖子不存在");
        }
        forum.setDeleteFlag(1);
        forum.setUpdateTime(LocalDateTime.now());
        int count = forumMapper.updateById(forum);
        if(count != 1) {
            throw new CommonException("删除失败");
        }
    }
}
